import json
import requests
from urllib import parse

from django.contrib.auth import login
from django.shortcuts import redirect, reverse
from django.utils import timezone as dj_timezone

from ceph.ceph_settings import get_yunkun_config
from core.aai.authentication import YunKunCodeDecode


class YunKunSignIn(YunKunCodeDecode):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    @classmethod
    def as_view(cls):
        return cls().yunkun_login_callback

    def yunkun_login_callback(self, request, *args, **kwargs):
        """
        第三方科技云认证联盟yunkun登录回调视图
        """
        code = request.GET.get('code', None)
        if not code:
            return self.yunkun_signin_failed()

        local_endpoint, yunkun_auth_endpoint, _, _ = get_yunkun_config()

        # local_endpoint = local_endpoint.rstrip('/')
        yunkun_auth_endpoint = yunkun_auth_endpoint.rstrip('/')

        if not local_endpoint or not yunkun_auth_endpoint:
            return self.yunkun_signin_failed()

        base_url = f'{yunkun_auth_endpoint}/open/api/AAILogin/dealCode'
        query = parse.urlencode(query={'code': f'{code}'})
        url = f'{base_url}?{query}'
        r = requests.post(url=url)

        jwt_key = json.loads(r.text)
        if jwt_key['code'] >= 400:
            return self.yunkun_signin_failed()

        payload_token = self.decode(jwt_key['data']['accessToken'])
        user = self.get_user(validated_token=payload_token)

        # 标记当前为科技云通行证登录用户
        if user.third_app != user.THIRD_APP_KJY:
            user.third_app = user.THIRD_APP_KJY
            user.last_active = dj_timezone.now()
            user.save(update_fields=['third_app', 'last_active'])

        login(request, user)  # 登录用户
        return redirect(to=reverse('buckets:bucket_view'))

    @classmethod
    def yunkun_signin_failed(cls, next_to=None):
        """
        登出科技云账户

        :param next_to: 登出后重定向的url
        :return:
        """
        url = next_to if next_to else '/'
        return redirect(to=url)
